layui.config({
    base: "static/layui/module/"
}).extend({
    dynamicCondition: 'dynamicCondition/dynamicCondition',
    excel: 'excel/excel'
}).use(['form', 'layer', 'jquery', 'table', 'laydate', 'upload', 'dynamicCondition','excel','laytpl'], function () {
    var layer = layui.layer,
        $ = layui.jquery,
        upload = layui.upload,
        element = layui.element,
        excel = layui.excel,
        laytpl = layui.laytpl,
        table = layui.table,
        dynamicCondition = layui.dynamicCondition;

    table.render({
        elem: '#table'
        ,title: '列表'
        ,url: '/manage/common/list/inventory'
        ,method: 'post'
        ,height: 'full-100'
        ,page: true //开启分页
        ,limit: 20
        ,limits: [20, 30, 40, 50, 60, 70, 80, 90, 100]
        ,loading: true
        ,cols: [[
            { type: 'radio' },
            { field: 'order', title: '序号',align:'center',templet: function (data) {
                    return data.LAY_TABLE_INDEX + 1
                }},
            { field: 'cusCode', title: '供应商编码' },
            { field: 'cusName', title: '供应商名称' },
            { field: 'material', title: '料号' },
            { field: 'standard', title: '标准值' },
            { field: 'growUp', title: '增长值' },
            { field: 'storeName', title: '仓库' }
        ]]
        ,text: {
            none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        }
        ,toolbar: '#tableToolbar'
        ,defaultToolbar: ['filter']
    });

    var dataFields = object.dataFields;

    top_dc = undefined;

    dc = dynamicCondition.create({
        fields: dataFields
        ,tableId: "table"
        ,conditionTextId: "#findMsg"
        ,type: "complex"
        ,requestDataType: "json"
        ,counts: 10
        ,queryCallBack: function (requestData) {
        }
        ,afterOpen: function (_dc) {
            top_dc = _dc;
        }
    });

    table.on('toolbar(table)', function(obj){
        var tableCheckData = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'find':
                dc.open();
                break;
            case 'add':
                layer.open({
                    type: 2
                    ,title: '新增'
                    ,area: ['50%', '100%']
                    ,content: '/manage/inventory/addHtml'
                    ,btn: ['保存', '取消']
                    ,offset: 'r'
                    ,yes: function (index, layero) {
                        var iframeWindow = $(layero).find("iframe")[0].contentWindow;
                        var data = iframeWindow.getFormDataAndValidate();
                        if (!data[0]) {
                            return;
                        }
                        var master = data[1];

                        let dataFlag = []
                        let flag = false;
                        //数据校验
                        $.each(master,function (name,val) {
                            if (!dataFlag.includes(name)) {
                                if (!val && val !== false){
                                    flag = true;
                                }
                            }
                        })
                        if (flag){
                            layer.msg("必填项未填写！", {
                                icon: 2,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            });
                            return;
                        }
                        let dataClass = ['ok','error','wait']
                        let dataClassTwo = ['B','C','D','E','F','G','H','I']
                        if (master.classType == 'A'){
                            if (!dataClass.includes(master.storeType)){
                                layer.msg("当前料号是产成品！仓库只能选择产成品分组的", {
                                    icon: 2,
                                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                });
                                return;
                            }
                        }else {
                            if (!dataClassTwo.includes(master.storeType)){
                                layer.msg("料号仓库选择错误！", {
                                    icon: 2,
                                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                });
                                return;
                            }
                        }
                        var shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
                        $.post("/manage/common/add", {url: object.url, obj: JSON.stringify(master)}, function (d) {
                            if (d.code == '200') {
                                top.layer.alert("新增成功", {icon: 1});
                                table.reload('table');
                            } else {
                                top.layer.msg("新增失败," + d.msg, {icon: 2});
                            }
                            top.layer.close(shadeIndex);
                            layer.close(index);
                        }, "json")
                    }
                });
                break;
            case 'upd':
                var data = tableCheckData.data;
                if (data.length == 0) {
                    layer.msg("请选择要修改的数据");
                    return;
                }
                ;
                if (data.length != 1) {
                    layer.msg("请选择单条数据");
                    return;
                }
                ;
                var index = layer.open({
                    type: 2
                    ,title: '修改'
                    ,area: ['50%', '100%']
                    ,content: '/manage/common/editHtml/' + object.url + '/' + data[0].id
                    ,btn: ['保存', '取消']
                    ,offset: 'r'
                    ,yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWindow = $(layero).find("iframe")[0].contentWindow;
                        var d = iframeWindow.getFormDataAndValidate();
                        if (!d[0]) {
                            return;
                        }
                        var master = d[1];
                        master.id = data[0].id;

                        var shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
                        $.post("/manage/common/update", {url: object.url, obj: JSON.stringify(master)}, function (d) {
                            if (d.code == '200') {
                                top.layer.msg("修改成功", {icon: 1});
                                table.reload('table');
                            } else {
                                top.layer.msg("修改失败," + d.msg, {icon: 2});
                            }
                            top.layer.close(shadeIndex);
                            layer.close(index);
                        }, "json")
                    }
                });
                break;
            case 'delete':
                if (tableCheckData.data.length == 0) {
                    layer.msg("请选择要删除的数据");
                    return;
                }
                top.layer.confirm('是否删除?', {icon: 3, title: '提示'}, function (index) {
                    var ids = new Array();
                    $.each(tableCheckData.data, function (index, e) {
                        ids.push(e.id);
                    });
                    var shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
                    $.ajax({
                        url: "/manage/common/delete/" + object.url,
                        type: "post",
                        data: JSON.stringify(ids),
                        contentType: "application/json",
                        success: function (d) {
                            if (d.code == '200') {
                                top.layer.alert("删除成功", {icon: 1});
                                table.reload('table');
                            } else {
                                top.layer.alert("删除失败," + d.msg, {icon: 2});
                            }
                            top.layer.close(shadeIndex);
                        },
                        error: function () {
                            top.layer.close(shadeIndex);
                            alert("删除失败！");
                        }
                    });
                    top.layer.close(index);
                });
                break;
            case 'disable':
                if (tableCheckData.data.length != 1) {
                    layer.msg("请选择要启用|禁用的数据");
                    return;
                }
                top.layer.confirm('是否' + tableCheckData.data[0].disable ? '禁用' : '启用' + '?', {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    var ids = new Array();
                    $.each(tableCheckData.data, function (index, e) {
                        ids.push(e.id);
                    });
                    var shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
                    $.ajax({
                        url: "/manage/common/disable/" + object.url,
                        type: "post",
                        data: JSON.stringify(ids),
                        contentType: "application/json",
                        success: function (d) {
                            if (d.code == '200') {
                                top.layer.msg("操作成功", {icon: 1});
                                table.reload('table');
                            } else {
                                top.layer.msg("操作失败," + d.msg, {icon: 2});
                            }
                            top.layer.close(shadeIndex);
                        },
                        error: function () {
                            top.layer.close(shadeIndex);
                            alert("操作失败！");
                        }
                    });
                    top.layer.close(index);
                });
                break;
            case 'download':
                layer.confirm('确定要导出数据并下载到本地吗？', function (index) {
                    var conditionArray = new Array();
                    if (top_dc != undefined) {
                        for (let i in top_dc.cacheCondition) {
                            if (top_dc.cacheCondition[i].conditionValueLeftVal.value != ''
                                || top_dc.cacheCondition[i].conditionValueRightVal.value != '' || top_dc.cacheCondition[i].conditionValueVal.value != '') {
                                var condition = {
                                    field: top_dc.cacheCondition[i].conditionFieldVal
                                    , type: top_dc.cacheCondition[i].conditionOptionVal
                                    , right: top_dc.cacheCondition[i].conditionValueRightVal.value
                                    , left: top_dc.cacheCondition[i].conditionValueLeftVal.value
                                    , value: top_dc.cacheCondition[i].conditionValueVal.value
                                }
                                conditionArray.push(condition);
                            }
                        }
                    }
                    window.location.href = "/manage/common/download?url=" + object.url + "&condition=" + encodeURI(JSON.stringify(conditionArray));
                    layer.close(index);
                });
                break;
            case 'import':
                layer.confirm('确认导入？', {
                        btn: ['覆盖导入','取消'] //按钮
                    }
                    ,function () {
                        $("#uploadExcel")[0].click();
                    })
                break;
        };
    })

    upload.render({
        elem: '#uploadExcel'
        ,accept: 'file' //普通文件
        ,exts: 'xlsx|xls'
        ,auto: false
        ,choose: function(obj){
            var files = obj.pushFile()
            var fileArr = Object.values(files)// 注意这里的数据需要是数组，所以需要转换一下
            var fields = {
                'material' : 'C',
                'growUp' : 'G',
                'storeType' : 'H'
            }
            // 用完就清理掉，避免多次选中相同文件时出现问题
            for (var index in files) {
                if (files.hasOwnProperty(index)) {
                    delete files[index]
                }
            }
            $('#uploadExcel').next().val('');
            uploadExcel('manage/inventory/upload/',fields,fileArr,excel,layer,laytpl,element)
        }
    });

    function uploadExcel(url,fields,files,excel,layer,laytpl,element) {
        try {
            excel.importExcel(files, {
                // 读取数据的同时梳理数据
                fields : fields
            }, function(data) {
                // 如果不需要展示直接上传，可以再次 $.ajax() 将JSON数据通过 JSON.stringify() 处理后传递到后端即可
                var sheetTab = undefined;

                layer.open({
                    title : '文件转换结果',
                    type: 1,
                    btn: ["确定","取消"],
                    area: [ '80%', '60%' ],
                    tipsMore : true,
                    content : laytpl($('#LAY-excel-export-ans').html()).render({
                        data : data,
                        files : files
                    }),
                    success : function(layero, index) {
                        element.on('tab(sheet)', function(data){
                            sheetTab = this.getAttribute('lay-id');
                        });
                    }
                    ,yes: function(index, layero){
                        let itm = layer.load(0, { shade: 0.3 });
                        if(sheetTab == undefined){
                            layer.msg("请先选择要导入的sheet页！",{icon:2});
                            return;
                        }
                        var result = data[0][sheetTab];
                        if(result.length < 3){
                            layer.msg("导入的sheet页没有数据！",{icon:2});
                            return;
                        }
                        var pushData = [];
                        $.each(result,function(index,e){
                            if(index > 1){
                                pushData.push(e);
                            }
                        });
                        var count = 0;
                        for(var i in pushData[0]) {
                            if(pushData[0].hasOwnProperty(i)) {
                                count++;
                            }
                        }
                        var dateField = [];
                        for(var i in fields) {
                            if(fields.hasOwnProperty(i)) {
                                count--;
                            }
                            if(fields[i].indexOf('time') || fields[i].indexOf('Time') || fields[i].indexOf('date') || fields[i].indexOf('Date')){
                                dateField.push(fields[i]);
                            }
                        }
                        if(count != 0){
                            alert('导入模板错误,导出的excel即为导入的模板！');
                            return;
                        }
                        try {
                            $.post(url, {data: JSON.stringify(pushData)}, function (d) {
                                if (d.code == '200') { //上传成功
                                    if (d.data) {
                                        layer.alert("导入成功,存在共用物料,请联系管理员核对！");
                                    } else {
                                        layer.alert("导入成功！");
                                    }
                                    table.reload('table');
                                } else {
                                    layer.alert("导入失败," + d.msg);
                                }
                            });
                        } catch (e) {
                            layer.alert("系统异常！");
                        } finally {
                            layer.close(itm)
                        }
                        layer.close(index); //如果设定了yes回调，需进行手工关闭
                    }
                })
            })
        } catch (e) {
            layer.alert(e.message)
        }
    }


})